package edu.chl.dat076.datesite.entities;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;

/**
 *
 * @author Daniel, Christoffer
 */
@Entity
public class Conversation implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
	@ManyToMany
	List<SiteUser> users;
	
    @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
    private List<Message> messages;
	


    public Conversation() {
    }
	
	public Conversation(SiteUser user1, SiteUser user2) {
		users = new ArrayList<SiteUser>();
		this.users.add(user1);
		this.users.add(user2);
	}

	public Conversation(List<SiteUser> users) {
		this.users = users;
	}


    public List<Message> getMessages() {
        //return messages;
		if (messages.size() > 1) {
			List<Message> temp = new ArrayList<Message>();

			for (int i = 0; i < messages.size(); i++) {
				temp.add(messages.get(messages.size()-1-i));
			}
			
			return temp;
		} else {
			return messages;
		}
    }

    public void setMessages(List<Message> messages) {
        this.messages = messages;
    }
    
    public void addMessage(Message message){
		if (messages == null) {
			messages = new ArrayList<Message>();
		}
        messages.add(message);
    }
    
    public SiteUser getUser1() {
        return users.get(0);
    }

    public SiteUser getUser2() {
        return users.get(1);
    }

	public List<SiteUser> getUsers() {
		return users;
	}

	public void setUsers(List<SiteUser> users) {
		this.users = users;
	}
    
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Conversation)) {
            return false;
        }
        Conversation other = (Conversation) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        
        
        StringBuilder sb = new StringBuilder();
        
        
        for (Message message : messages){
            sb.append(message).append("\n\n");
        }
        
        
        return sb.toString();
    }
    
}
